package org.example.sword2offer.primary;

import java.util.ArrayList;

/**
 * @author: lynn
 * @Descript: n*n 矩阵及其简单做法
 * @date: 2021/5/13 23:16
 * @version: 1.0
 */
public class Q19_NN_PrintMatrix {

        public static void main(String[] args) { //顺时针顺序
            int[][] array={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
            System.out.println(printMatrix(array));
        }
        private static ArrayList<Integer> printMatrix(int [][] matrix) {
            ArrayList<Integer> res = new ArrayList<Integer>();
            if(matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) return res;
            int left = 0, top = 0, right = matrix.length - 1, bottom = matrix[0].length - 1;//m是行，n是列
            while(left < right && top < bottom){  //fixme (向)右下左上跑 ,while 没了
                for (int i=left;i<right;i++) res.add(matrix[top][i]); //向右
                for (int i=top;i<bottom;i++) res.add(matrix[i][right]);//向下
                for (int i=right;i>left;i--) res.add(matrix[bottom][i]);//向左
                for (int i=bottom;i>top;i--) res.add(matrix[i][left]);//向上
                left++;top++;right--;bottom--; //跑完就缩圈
            }
            if(top==bottom){ // fixme 剩余当行列,直接遍历完
                for (int i=left;i<=right;i++) res.add(matrix[top][i]); //fixme i<=right
            }else if (left==right){
                for (int i=top;i<bottom;i++) res.add(matrix[i][right]);
            }
            return res;
        }
}
